/**
 * axios 配置 拦截器
 */
import router from '../router'
window.axios = require('axios')

const SERVER_CODE_ERROR = '网络不给力，请刷新重试。';//服务器未知错误，非正常处理

/**
 * axios request headers config
 */
window.axios.defaults.headers.common = {
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}

/**
 * 拦截请求处理
 */
window.axios.interceptors.request.use(function (request) {
  let method = request.method
  let data = '';
  if (method == 'post') {
    data = request.data ? request.data : {}
  } else {
    let isLoading = getUrlParam('loading', request.url)
    data = { loading: isLoading }
  }
  if (data.loading && data.loading) {
    alphaHub.$emit('display');//展示request loading
  }
  return request
})

/**
 * 拦截响应处理
 */
window.axios.interceptors.response.use(
  function (response) {
    if (!response) {
      return Promise.reject({ 'msg': '服务器错误', 'error': '1' })
    }
    setTimeout(() => {
      alphaHub.$emit('hide')
    }, 200)

    let url = response.config.url;
    if (!url.includes('geetest')) {
      let res = response.data
      // error [0:正常成功 1:失败 9000:特殊提示返回（特殊事件处理）1111：版本滞后]
      if (res.error === 0) {
        return Promise.resolve(res)
      } else if (res.error === 9998) {
        // setCookie('cookiekey', '');//登录失效后清除浏览器端cookie值
        const IGNORE_HASH = ['#/index/iosDownloadPre', '#/index/test', '#/index/invite', '#/index/inviteLink']
        let hash = window.location.hash
        // 过滤若干无需登录页面
        if (!IGNORE_HASH.includes(hash)) {
          // alphaHub.showToast({ msg: res.msg });
          // window.location.href = '/game/#/register';

          // 邀请链接-验证码
          let invite_code = getUrlParam('invite_code')
          router.push({ name: 'register', query: { invite_code: invite_code } })
        }
        return Promise.reject(res)
      } else {
        alphaHub.showToast({ msg: res.msg })
        return Promise.reject(res)
      }
    }
    return response
  },
  function (error) {
    try {
      alphaHub.showToast({
        msg: SERVER_CODE_ERROR
      })
    } catch (err) {
      alert(SERVER_CODE_ERROR)
    }
    setTimeout(() => {
      alphaHub.$emit('hide')
    }, 200)
    // window.location.href = '/';
    return Promise.reject(error)
  }
)

/** 获取URL参数 */
function getUrlParam(param, url = window.location.href) {
  let reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)')
  let queries = url.split('?')[1] + ''
  let r = queries.match(reg)
  if (r != null) { return decodeURI(r[2]) }// 对encodeURI编码处理过的uri进行解码
  return null
}

// example: var url = 'http://localhost:8080/#/index/sixSkills?name=1&age=88';
// var params = getUrlParams(url);
// console.log(params);//{name:1,age:88}
function getUrlParams(url) {
  let q = {}
  url.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => q[k] = v)
  return q
}
